﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;

namespace QLThuChi.OtherForms
{
    #region Using
    using QLThuChi.Helpers;
    using QLThuChi.Models;
    using QLThuChi.Repositories;
    #endregion

    /// <summary>
    /// tuansl added: manage loai don vi corresponding with menus in app
    /// </summary>
    public partial class FrmQuanLyVLXD: Office2007Form
    {
        // tuansl added: event handler to transfer data to other forms
        public EventHandler Handler { get; set; }
        // Hidden files are used to store ids 
        private DevComponents.DotNetBar.Controls.TextBoxX txtMaDonViTinh;
        // ---------------- E -----------------

        public FrmQuanLyVLXD(bool enableChon = false)
        {
            InitializeComponent();
            InitHiddenFields();
            InitGridView();
            btnChon.Enabled = enableChon;
        }

        /// <summary>
        /// Init hidden fields
        /// </summary>
        public void InitHiddenFields()
        {
            // Add a new textbox
            txtMaDonViTinh = new DevComponents.DotNetBar.Controls.TextBoxX
            {
                Name = "txtMaDonViTinh",
                Text = ""
            };
            txtMaDonViTinh.Visible = false;

        }

        private void FrmQuanLyVLXD_Load(object sender, EventArgs e)
        {
            LoadData();
            // No choose any item
            dtgvDataList.ClearSelection();
        }

        private void btnThemMoi_Click(object sender, EventArgs e)
        {
            var errorText = "";
            if (!ValidateInput(EnumUpdateMode.INSERT, ref errorText))
            {
                MessageBox.Show(errorText, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (ActionAdd())
            {
                MessageBox.Show("Lưu dữ liệu thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                LoadData();
            }
            else
            {
                MessageBox.Show("Lưu dữ liệu thất bại", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnXoa_Click(object sender, EventArgs e)
        {
            var errorText = "";
            if (!ValidateInput(EnumUpdateMode.DELETE, ref errorText))
            {
                MessageBox.Show(errorText, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (MessageBox.Show("Bạn có chắc chắn xóa dòng này không?", "Xóa", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                if (ActionDelete())
                {
                    MessageBox.Show("Xóa dữ liệu thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    LoadData();
                }
                else
                {
                    MessageBox.Show("Xóa dữ liệu thất bại", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void btnLuu_Click(object sender, EventArgs e)
        {
            var errorText = "";
            if (!ValidateInput(EnumUpdateMode.UPDATE, ref errorText))
            {
                MessageBox.Show(errorText, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (ActionUpdate())
            {
                MessageBox.Show("Cập nhật dữ liệu thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                LoadData();
            }
            else
            {
                MessageBox.Show("Cập nhật dữ liệu thất bại", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnThoat_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            txtMaVLXD.Text = "";
            txtTenVLXD.Text = "";
        }

        private void dtgvDataList_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dtgvDataList.SelectedRows == null || dtgvDataList.SelectedRows.Count == 0)
                return;

            txtMaVLXD.Text = dtgvDataList.SelectedRows[0].Cells["MaVLXD"].Value.ToString();

            var item = VLXDRepository.SelectByID(int.Parse(txtMaVLXD.Text));

            txtTenVLXD.Text = item.TenVLXD;
            txtDonViTinh.Text = item.DonViTinh.TenDonViTinh;
            txtMaDonViTinh.Text = item.MaDonViTinh.ToString();
        }

        private void btnChon_Click(object sender, EventArgs e)
        {
            var errorText = "";
            if (!ValidateInput(EnumUpdateMode.CHOOSING, ref errorText))
            {
                MessageBox.Show(errorText, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            var id = int.Parse(txtMaVLXD.Text);
            var name = VLXDRepository.SelectByID(id).TenVLXD;
            TransferDataInfo(this, new MyEvent(id + "#" + name));
        }

        /// <summary>
        /// Init structure of gridview
        /// </summary>
        private void InitGridView()
        {
            dtgvDataList.AutoGenerateColumns = false;
            dtgvDataList.Columns.Clear();

            DataGridViewTextBoxColumn objColumn = new DataGridViewTextBoxColumn
            {
                HeaderText = "Mã VLXD",
                DataPropertyName = "MaVLXD",
                Name = "MaVLXD",
                Width = (int)((dtgvDataList.Width - dtgvDataList.RowHeadersWidth) * 0.3)
            };
            dtgvDataList.Columns.Add(objColumn);

            objColumn = new DataGridViewTextBoxColumn
            {
                HeaderText = "Tên VLXD",
                DataPropertyName = "TenVLXD",
                Name = "TenVLXD",
                Width = (int)((dtgvDataList.Width - dtgvDataList.RowHeadersWidth) * 0.5 - 1)
            };
            dtgvDataList.Columns.Add(objColumn);

            objColumn = new DataGridViewTextBoxColumn
            {
                HeaderText = "Đơn vị tính",
                DataPropertyName = "TenDonViTinh",
                Name = "TenDonViTinh",
                Width = (int)((dtgvDataList.Width - dtgvDataList.RowHeadersWidth) * 0.2 - 1)
            };
            dtgvDataList.Columns.Add(objColumn);
        }

        /// <summary>
        /// Load data from DB
        /// </summary>
        private void LoadData()
        {
            var lstItem = VLXDRepository.SelectAll();

            var dt = new DataTable();
            dt.Columns.Add("MaVLXD");
            dt.Columns.Add("TenVLXD");
            dt.Columns.Add("TenDonViTinh");

            for (int i = 0; i < lstItem.Count; i++)
            {
                dt.Rows.Add(lstItem[i].MaVLXD, lstItem[i].TenVLXD, lstItem[i].DonViTinh.TenDonViTinh);
            }

            DataView objTimeSheetDV = new System.Data.DataView(dt);
            objTimeSheetDV.AllowNew = false;
            dtgvDataList.AutoGenerateColumns = false;
            dtgvDataList.DataSource = objTimeSheetDV;

            dtgvDataList.ClearSelection();
        }

        /// <summary>
        /// Validate user input
        /// </summary>
        /// <param name="isUpdate"></param>
        /// <returns></returns>
        private bool ValidateInput(EnumUpdateMode mode, ref string errorText)
        {
            // Mode update -> checking MaVLXD is exists on textbox
            if (mode == EnumUpdateMode.UPDATE || mode == EnumUpdateMode.DELETE || mode == EnumUpdateMode.CHOOSING)
            {
                if (txtMaVLXD.Text == "")
                {
                    errorText = "Vui lòng chọn VLXD";
                    return false;
                }
            }
            if (mode != EnumUpdateMode.DELETE)
            {
                if (txtTenVLXD.Text == "")
                {
                    errorText = "Vui lòng nhập tên VLXD";
                    return false;
                }
                if (txtMaDonViTinh.Text == "")
                {
                    errorText = "Vui lòng chọn đơn vị tính";
                    return false;
                }
            }

            return true;
        }

        /// <summary>
        /// Add a new item to DB
        /// </summary>
        /// <returns></returns>
        private bool ActionAdd()
        {
            try
            {
                var item = new VLXD
                {
                    TenVLXD = txtTenVLXD.Text,
                    MaDonViTinh = int.Parse(txtMaDonViTinh.Text)
                };
                if (!VLXDRepository.Insert(item))
                {
                    return false;
                }
                EraseTextboxes();
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// Erase data in textboxes when mode is insert
        /// </summary>
        public void EraseTextboxes()
        {
            txtTenVLXD.Text = "";
            txtMaDonViTinh.Text = "";
            txtDonViTinh.Text = "";
        }

        /// <summary>
        /// Update item with specificed ID
        /// </summary>
        /// <returns></returns>
        private bool ActionUpdate()
        {
            try
            {
                var item = VLXDRepository.SelectByID(int.Parse(txtMaVLXD.Text));
                item.TenVLXD = txtTenVLXD.Text;
                item.MaDonViTinh = int.Parse(txtMaDonViTinh.Text);
                return VLXDRepository.Save();
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// Delete item with specified ID
        /// </summary>
        /// <returns></returns>
        private bool ActionDelete()
        {
            try
            {
                return VLXDRepository.Delete(int.Parse(txtMaVLXD.Text));
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// tuansl added: function is used to transfer data when event would be raised
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void TransferDataInfo(object sender, MyEvent e)
        {
            this.Close();
            this.Handler(this, e);
        }

        private void btnChonDonViTinh_Click(object sender, EventArgs e)
        {
            FrmQuanLyDonViTinh frm = new FrmQuanLyDonViTinh(true);
            frm.Handler += GetDonViTinh;
            frm.ShowDialog();
        }

        public void GetDonViTinh(object sender, EventArgs e)
        {
            var eventType = (MyEvent)e;
            string[] comp = eventType.Data.Split(new char[] { '#' });

            txtMaDonViTinh.Text = comp[0];
            txtDonViTinh.Text = comp[1];
        }
    }
}